package com.ipzoe.file.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ipzoe.common.exception.CustomException;
import com.ipzoe.file.domain.FileInfoDO;
import com.ipzoe.file.mapper.FileInfoDOMapper;
import com.ipzoe.file.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 * AbstractIFileService 抽取类,根据xfhy.file-server.type 实例化具体对象
 * </p>
 * @author Eric
 * @date 2020/6/12
 */
@Slf4j
public abstract class AbstractFileDOService extends ServiceImpl<FileInfoDOMapper, FileInfoDO> implements FileInfoDOService {

    private static final String FILE_SPLIT = ".";

    @Override
    public FileInfoDO upload(MultipartFile file, String folder) {
        FileInfoDO fileInfo = FileUtil.getFileInfo(file);
        FileInfoDO oldFileInfo = baseMapper.selectById(fileInfo.getId());
        if (oldFileInfo != null) {
            return oldFileInfo;
        }
        if (!fileInfo.getName().contains(FILE_SPLIT)) {
            throw new IllegalArgumentException("缺少后缀名");
        }
        // 设置文件来源
        fileInfo.setSource(fileType());
        //设置文件保存路径
        fileInfo.setPath(FileUtil.generateDateTypeParentPath(folder) + fileInfo.getName());

        try {
            uploadFile(file, fileInfo);
            // 将文件信息保存到数据库
            baseMapper.insert(fileInfo);

            return fileInfo;
        } catch (IOException e) {
            log.error("上传那文件错误！", e);
            throw new CustomException(500,"上传那文件错误！");
        }
    }

    /**
     * 文件来源
     *
     * @return
     */
    protected abstract String fileType();

    /**
     * 上传文件
     *
     * @author Eric
     * @date 2020/3/25
     */
    protected abstract void uploadFile(MultipartFile file, FileInfoDO fileInfo) throws IOException;

    /**
     * 删除文件
     *
     * @param id 文件id
     */
    @Override
    public void delete(String id) {
        FileInfoDO fileInfo = baseMapper.selectById(id);
        if (fileInfo != null) {
            baseMapper.deleteById(fileInfo.getId());
            this.deleteFile(fileInfo);
        }
    }

    /**
     * 删除文件资源
     *
     * @param fileInfo
     * @return
     */
    protected abstract boolean deleteFile(FileInfoDO fileInfo);

}
